package com.marketlive.system.text;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

public class PhoneNumberFormat
{
  private Log log = LogFactory.getLog(PhoneNumberFormat.class);

  private Map phoneMasks = new HashMap();

  private static PhoneNumberFormat singleton = null;

  private PhoneNumberFormat()
  {
    singleton = this;
  }

  public static PhoneNumberFormat getInstance()
  {
    return singleton;
  }

  public void setPhoneMasks(Map phoneMasks)
  {
    this.phoneMasks = phoneMasks;
  }

  public String getPhoneMask(String countryCode)
  {
    return (String)this.phoneMasks.get(countryCode);
  }

  public int getPhoneLength(String countryCode)
  {
    String phoneMask = getPhoneMask(countryCode);
    if (phoneMask != null) {
      return StringUtils.countOccurrencesOf(phoneMask, "#");
    }

    return 0;
  }

  public String format(String phoneNumber, String countryCode)
  {
    if (phoneNumber == null) {
      return null;
    }

    String digits = phoneNumber.replaceAll("[^0-9]", "");

    String phoneMask = getPhoneMask(countryCode);
    if (phoneMask != null)
    {
      if (digits.length() == StringUtils.countOccurrencesOf(phoneMask, "#")) {
        for (int i = 0; i < digits.length(); i++) {
          phoneMask = phoneMask.replaceFirst("#", String.valueOf(digits.charAt(i)));
        }
        return phoneMask;
      }
    }

    return phoneNumber;
  }
}